<?php

/**
 * view actions.
 *
 * @package    raidpoints
 * @subpackage view
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class viewActions extends sfActions
{
    public function executeIndex(sfWebRequest $request)
    {
        $this->forward("view", "points");
    }

    public function executePoints(sfWebRequest $request)
    {
        $query = Doctrine::getTable('ViewRaidPlayers')
                ->getGuilded()
                ->andWhere("altrank=?", 0)
                ->andWhere("altid=?", 1)
                ->andWhere("raidid IS NOT NULL")
                ->andWhere("raidid=?", 1)
                ->andWhere('lifetime > ?', 0);
        //echo $query->getDql();
        $this->players = $query->execute();

        $query = Doctrine::getTable("Filter")
                ->createQuery('f')
                ->orderBy("sort")
                ->leftJoin("f.FilterTalent ft")
                ->leftJoin("f.FilterClass fc")
                ->leftJoin("ft.Talent ftt")
                ->leftJoin("ftt.PClass fttc")
                ->leftJoin("fc.PClass fcc");
        $this->filters = $query->execute();

        $query = Doctrine::getTable("Rank")
                ->createQuery('f')
                ->orderBy("sort");
        $result = $query->execute();

        $this->ranks = array();
        foreach ($result as $rank)
        {
            $this->ranks[$rank['name']] = $rank['name'];
        }

        $this->name = "points";

        $response = $this->getResponse();
        $response->setTitle(sfConfig::get('app_guild').sfConfig::get('app_delimiter').'Raid Points');
    }

    public function executePlayerView(sfWebRequest $request)
    {
        $ajax = false;
        if ($this->getRequest()->isXmlHttpRequest())
        {
            $this->getContext()->getConfiguration()->loadHelpers('Partial');
            $this->getContext()->getConfiguration()->loadHelpers('Url');
            $ajax = true;
        }

        $tabs = array();
        $tabs['items'] = array('tab' => 'item', 'id' => 'tabsAjax-item', 'sort' => $request->getParameter('sort', 'dt'), 'order' => $request->getParameter('order', 'desc'));
        $tabs['points'] = array('tab' => 'point', 'id' => 'tabsAjax-point', 'sort' => $request->getParameter('sort', 'dt'), 'order' => $request->getParameter('order', 'desc'));
        $tabs['raids'] = array('tab' => 'raid', 'id' => 'tabsAjax-raid', 'sort' => $request->getParameter('sort', 'dt'), 'order' => $request->getParameter('order', 'desc'));

        $playerinfo = $this->getRoute()->getObject();
        $text = "";
        $times = array();

        if (!$ajax || ($ajax && $request->hasParameter('itemPage')) )
        {
            $orderby = $request->getParameter('sort', 'dt')." ".$request->getParameter('order', 'desc');
            $query = Doctrine::getTable("ViewHistory")
                    ->createQuery()
                    ->select("reason, reasonid, dt, itemid, SUM(value) as 'value'")
                    ->where("raidid=?", $playerinfo->getRaidid())
                    ->andWhere("playerid=?", $playerinfo->getId())
                    ->andWhere("ttype=?", 'I')
                    ->groupBy("dt");
            if ($orderby != "")
                $query->addOrderBy($orderby);

            $itemsPager = new sfDoctrinePager('ViewHistory', 10);
            $itemsPager->setQuery($query);
            $itemsPager->setPage($request->getParameter('itemPage', 1));
            $itemsPager->init();
            $result = $itemsPager->getResults();

            $items = array();
            if ($result->count() > 0)
            {
                foreach ($result as $history)
                {
                    $array = array();
                    $array['itemid'] = $history['itemid'];
                    $array['reason'] = $history['reason'];
                    $array['dt'] = $history['dt'];
                    $array['isItem'] = false;
                    $match = preg_match('/\[(.*)\]/i', $array['reason'], $words);
                    if ($match)
                    {
                        $array['isItem'] = true;
                        $array['reason'] = $words[0];
                        if ($history['itemid'] == 0)
                        {
                            $match = preg_match_all('/[^:]+/i', $array['reason'], $item);
                            if (isset($item[0][1]))
                                $history['itemid'] = $item[0][1];
                        }
                    }
                    $array['value'] = $history["'value'"];
                    $array['quality'] = "q4";
                    $array['date'] = date('m/d/y h:i A', strtotime($history['dt']." GMT"));
                    $items[] = $array;
                }
            }

            $tabs['items']['value'] = $items;
            $tabs['items']['pager'] = $itemsPager;

            if ($ajax)
            {
                return $this->renderText(get_partial('tab/'.$tabs['items']['tab'],
                        array(
                        'tab' => $tabs['items'],
                        'ajax' => $ajax,
                        'url_for' => url_for("@view_player?raidslug=".$playerinfo->getRaidslug()."&fullname=".$playerinfo->getFullname())
                        ))) ;
            }
        }

        $times["Points"]["begin"] = microtime();
        if (!$ajax || ($ajax && $request->hasParameter('pointPage')) )
        {
            $orderby = $request->getParameter('sort', 'dt')." ".$request->getParameter('order', 'desc');
            if ($request->getParameter('sort', 'dt') != "reason")
                $orderby = $request->getParameter('sort', 'dt')." ".$request->getParameter('order', 'desc');
            $query = Doctrine::getTable("ViewHistory")
                    ->createQuery()
                    ->select("reason, dt, itemid, SUM(value) as 'value'")
                    ->where("raidid=?", $playerinfo->getRaidid())
                    ->andWhere("playerid=?", $playerinfo->getId())
                    ->andWhere("ttype=?", 'P')
                    ->groupBy("dt")
                    ->orderBy($orderby);
            $pointsPager = new sfDoctrinePager('ViewHistory', 10);
            $pointsPager->setQuery($query);
            $pointsPager->setPage($request->getParameter('pointPage', 1));
            $pointsPager->init();

            $result = $pointsPager->getResults();
            $points = array();
            if ($result->count() > 0)
            {
                foreach ($result as $history)
                {
                    $array = array();
                    $array['itemid'] = $history['itemid'];
                    $array['reason'] = $history['reason'];
                    $array['dt'] = $history['dt'];
                    $array['isItem'] = false;
                    $match = preg_match('/\[(.*)\]/i', $array['reason'], $words);
                    if ($match)
                    {
                        $array['isItem'] = true;
                        $array['reason'] = $words[0];
                        if ($array['itemid'] == 0)
                        {
                            $match = preg_match_all('/[^:]+/i', $array['reason'], $item);
                            if (isset($item[0][1]))
                                $array['itemid'] = $item[0][1];
                        }
                    }
                    $array['value'] = $history["'value'"];
                    $array['quality'] = "q4";
                    $array['date'] = date('m/d/y h:i A', strtotime($history['dt']." GMT"));
                    $points[] = $array;
                }
            }

            $tabs['points']['value'] = $points;
            $tabs['points']['pager'] = $pointsPager;

            if ($ajax)
            {
                return $this->renderText(get_partial('tab/'.$tabs['points']['tab'],
                        array(
                        'tab' => $tabs['points'],
                        'ajax' => $ajax,
                        'url_for' => url_for("@view_player?raidslug=".$playerinfo->getRaidslug()."&fullname=".$playerinfo->getFullname())
                        ))) ;
            }
        }
        $times["Points"]["end"] = microtime();

        $times["Raids"]["begin"] = microtime();
        if (!$ajax || ($ajax && $request->hasParameter('raidPage')) )
        {
            $raids = array();
            $query = Doctrine::getTable("HistoryRaid")
                    ->createQuery('hr')
                    ->select("hr.scheduled_date")
                    ->where("hr.raidid=?", $playerinfo->getRaidid())
                    ->groupBy("hr.scheduled_date")
                    ->orderBy("hr.scheduled_date desc");
            $raidsPager = new sfDoctrinePager('HistoryRaid', 10);
            $raidsPager->setQuery($query);
            $raidsPager->setPage($request->getParameter('raidPage', 1));
            $raidsPager->init();

            $result = $raidsPager->getResults();
            if ($result->count() > 0)
            {
                $dates = array();
                foreach ($result as $history)
                {
                    $dates[] = $history['scheduled_date'];
                }

                $orderby = "";
                if ($request->getParameter('sort', 'dt') != "status")
                    $orderby = $request->getParameter('sort', 'dt')." ".$request->getParameter('order', 'desc');
                $query = Doctrine::getTable("HistoryGuild")
                        ->createQuery('hg')
                        ->select('dt, scheduled_date');
                if ($orderby != "")
                    $query->addOrderBy($orderby);
                foreach ($dates as $date)
                {
                    $query->orWhere("raidid=?", $playerinfo->getRaidid())
                            ->andWhere("scheduled_date=?", $date);
                }
                $guildResult = $query->execute();

                $guildRaids = array();
                foreach ($guildResult as $guild)
                {
                    if (!isset($guildRaids[$guild['scheduled_date']]))
                        $guildRaids[$guild['scheduled_date']] = array();
                    $guildRaids[$guild['scheduled_date']][$guild['dt']] = array('dt' => $guild['dt']);
                }

                $query = Doctrine::getTable("HistoryGuild")
                        ->createQuery('hg')
                        ->select('hg.dt, h.scheduled_date, h.waitlistflag')
                        ->innerJoin("hg.ViewGuildHistory h")
                        ->addOrderBy("h.dt desc");

                foreach ($dates as $date)
                {
                    $query->orWhere("h.raidid=?", $playerinfo->getRaidid())
                            ->andWhere("h.playerid=?", $playerinfo->getId())
                            ->andWhere("hg.scheduled_date=?", $date);
                }
                $playerResult = $query->execute();

                $playerRaids = array();
                foreach ($playerResult as $player)
                {
                    if (!isset($playerRaids[$player['ViewGuildHistory']['scheduled_date']]))
                        $playerRaids[$player['ViewGuildHistory']['scheduled_date']] = array();
                    $playerRaids[$player['ViewGuildHistory']['scheduled_date']][$player['dt']] = array('dt' => $player['dt'], 'waitlist' => $player['ViewGuildHistory']['waitlistflag']);
                }

                foreach ($guildRaids as $s => $guild)
                {
                    $array = array();
                    $array['date'] = date('m/d/y', strtotime($s." 00:00 GMT"));
                    ;
                    $array['block'] = array();
                    $i = 0;
                    $notMissed = false;
                    foreach ($guild as $dt => $r)
                    {
                        if (isset($playerRaids[$s][$dt]))
                        {
                            if ($playerRaids[$s][$dt]['waitlist'] == 1)
                            {
                                $array['block'][] = 'waitlist';
                                $notMissed = true;
                            }
                            else
                            {
                                $array['block'][] = 'raid';
                                $notMissed = true;
                            }
                        }
                        else
                        {
                            $array['block'][] = 'blank';
                            if ($i == 0)
                                $array['state'] = 'Late';
                            elseif ($i == count($guild[$dt])-1)
                                $array['state'] = (isset($array['state'])?($array['state'].' / '):'').'Left Early';
                        }
                    }
                    if (!$notMissed)
                        $array['state'] = "Missing";
                    else
                        $array['state'] = "Attended";
                    $raids[] = $array;
                }

                if ($request->getParameter('sort', 'dt') == "status")
                {
                    function cmp($a, $b)
                    {
                        print_r($a);
                        return strcmp($a['state'], $b['state']);
                    }
                    uasort($raids, "cmp");
                    $tabs['raids']['sort'] = "status";
                }
            }

            $tabs['raids']['value'] = $raids;
            $tabs['raids']['pager'] = $raidsPager;

            if ($ajax)
            {
                return $this->renderText(get_partial('tab/'.$tabs['raids']['tab'],
                        array(
                        'tab' => $tabs['raids'],
                        'ajax' => $ajax,
                        'url_for' => url_for("@view_player?raidslug=".$playerinfo->getRaidslug()."&fullname=".$playerinfo->getFullname())
                        ))) ;
            }
        }
        $times["Raids"]["end"] = microtime();

        $times["Attendance"]["begin"] = microtime();
        $attendance = array();
        $query = Doctrine::getTable("PlayerAttendance")
                ->createQuery()
                ->select("numdays, percent")
                ->where("raidid=?", $playerinfo->getRaidid())
                ->andWhere("playerid=?", $playerinfo->getId());
        $result = $query->execute();

        foreach ($result as $a)
        {
            $array['day'] = $a['numdays'];
            $array['perc'] = $a['percent'];
            $attendance[] = $array;
        }
        $times["Attendance"]["end"] = microtime();

        $times["PlayerTalent"]["begin"] = microtime();
        $query = Doctrine::getTable("PlayerTalent")
                ->createQuery('pt')
                ->innerJoin("pt.Talent t")
                ->where("pt.playerid=?", $playerinfo->getId());
        $result = $query->execute();

        $talentSpecs = array();
        foreach ($result as $talent)
            $talentSpecs[] = $talent->toArray();
        $times["PlayerTalent"]["end"] = microtime();

        $this->name = 'player';
        $this->playerinfo = $playerinfo;
        $this->attendance = $attendance;
        $this->tabs = $tabs;
        $this->talentSpecs = $talentSpecs;
        return;

        return $this->renderText(get_partial('ajax/player', array(
                'name' => 'player',
                'playerinfo' => $playerinfo,
                'attendance' => $attendance,
                'tabs' => $tabs,
                'talentSpecs' => $talentSpecs,
        )));
    }

    public function executeRaids(sfWebRequest $request)
    {
        $this->name = "raids";
        $ajax = false;
        $this->getContext()->getConfiguration()->loadHelpers('Url');
        if ($this->getRequest()->isXmlHttpRequest())
        {
            $this->getContext()->getConfiguration()->loadHelpers('Partial');
            $ajax = true;
        }
        $this->ajax = $ajax;

        $tab = null;

        $orderby = "scheduled_date desc";
        if ($request->getParameter('sort', 'scheduled_date') == "scheduled_date")
            $orderby = $request->getParameter('sort', 'scheduled_date')." ".$request->getParameter('order', 'desc');
        
        $query = Doctrine::getTable('HistoryRaid')
            ->createQuery("hr")
            ->where("raidid=?", 1)
            ->innerJoin("hr.Raid r");
        if ($orderby != "")
            $query->addOrderBy($orderby);

        $pager = new sfDoctrinePager('HistoryRaid', 15);
        $pager->setQuery($query);
        $pager->setPage($request->getParameter('page', 1));
        $pager->init();
        $raids = $pager->getResults();

        $tab['pager'] = $pager;
        $tab['sort'] = $request->getParameter('sort', 'scheduled_date');
        $tab['order'] = $request->getParameter('order', 'desc');
        $tab['id'] = $this->name."Container";
        $this->url_for = url_for(sfContext::getInstance()->getRouting()->getCurrentInternalUri(false));
        $this->get = "page";

        $query = Doctrine::getTable("History")
                ->createQuery("h")
                ->select("scheduled_date, sum(value), raidid")
                ->groupBy("scheduled_date")
                ->orderBy("scheduled_date desc");

        $query2 = Doctrine::getTable("History")
                ->createQuery("h")
                ->select("scheduled_date, sum(value), raidid")
                ->groupBy("scheduled_date")
                ->orderBy("scheduled_date desc");

        $query3 = Doctrine::getTable("History")
                ->createQuery("h")
                ->select("scheduled_date, count(distinct playerid)")
                ->groupBy("scheduled_date")
                ->orderBy("scheduled_date desc");

        $raidArray = array();
        foreach ($raids as $raid)
        {
            $query->orWhere("h.raidid=?", $raid['raidid'])
                    ->andWhere("h.scheduled_date=?", $raid['scheduled_date'])
                    ->andWhere("h.value > 0");
            $query2->orWhere("h.raidid=?", $raid['raidid'])
                    ->andWhere("h.scheduled_date=?", $raid['scheduled_date'])
                    ->andWhere("h.value < 0");
            $query3->orWhere("h.raidid=?", $raid['raidid'])
                    ->andWhere("h.scheduled_date=?", $raid['scheduled_date']);

            $raidArray[$raid['scheduled_date']] =
                    array(
                    "id" => $raid->getRaid()->getId(),
                    "name" => $raid->getRaid()->getName(),
                    "server" => $raid->getRaid()->getServer(),
                    "slug" => $raid->getRaid()->getSlug(),
                    "date" => $raid['scheduled_date'],
                    "gain" => 0,
                    "loss" => 0,
                    "players" => 0,
            );
        }
        $gainResult = $query->setHydrationMode(Doctrine::HYDRATE_SCALAR)->execute();
        $lossResult = $query2->setHydrationMode(Doctrine::HYDRATE_SCALAR)->execute();
        $playerResult = $query3->setHydrationMode(Doctrine::HYDRATE_SCALAR)->execute();

        foreach ($playerResult as $player)
        {
            $raidArray[$player['h_scheduled_date']]["players"] = $player['h_count'];
            //print_r($player);
        }

        foreach ($gainResult as $gain)
        {
            $raidArray[$gain['h_scheduled_date']]["gain"] = $gain['h_sum'];
            //print_r($gain);
        }

        foreach ($lossResult as $loss)
        {
            $raidArray[$loss['h_scheduled_date']]["loss"] = $loss['h_sum'];
            //print_r($loss);
        }

        //members points gain loss
        if ($request->getParameter('sort', 'scheduled_date') != "scheduled_date")
        {
            global $sort;
            $sort = $request->getParameter('sort', 'scheduled_date');
            function cmpa($a, $b)
            {
                global $sort;
                return strcmp($b[$sort], $a[$sort]);
            }
            function cmpd($a, $b)
            {
                global $sort;
                return strcmp($a[$sort], $b[$sort]);
            }
            if ($request->getParameter('order', 'asc') == "asc")
            {
                $tab['order'] = "asc";
                uasort($raidArray, "cmpd");
            }
            else
            {
                $tab['order'] = "desc";
                uasort($raidArray, "cmpa");
            }
            $tab['sort'] = $sort;
        }

        $this->tab = $tab;
        $this->raids = $raidArray;

        if ($ajax)
        {
            return $this->renderText(get_partial('view/raids',
                    array(
                    'tab' => $this->tab,
                    'url_for' => $this->url_for,
                    'get' => $this->get,
                    'name' => $this->name,
                    'raids' => $this->raids,
                    'ajax' => $this->ajax,
                    ))) ;
        }

        $response = $this->getResponse();
        $response->setTitle(sfConfig::get('app_guild').sfConfig::get('app_delimiter').'Raids');
    }

    public function executeRaidView($request)
    {
        $ajax = false;
        if ($this->getRequest()->isXmlHttpRequest())
        {
            $this->getContext()->getConfiguration()->loadHelpers('Partial');
            $this->getContext()->getConfiguration()->loadHelpers('Url');
            $ajax = true;
        }

        $raidinfo = $this->getRoute()->getObject();
        $text = "";

        $tabs = null;
        $tabs['players'] = array('tab' => 'player', 'id' => 'tabsAjax-player', 'sort' => $request->getParameter('sort', 'name'), 'order' => $request->getParameter('name', 'asc'));
        $tabs['items'] = array('tab' => 'item_player', 'id' => 'tabsAjax-itemplayer', 'sort' => $request->getParameter('sort', 'dt'), 'order' => $request->getParameter('order', 'desc'));
        $tabs['points'] = array('tab' => 'point', 'id' => 'tabsAjax-point', 'sort' => $request->getParameter('sort', 'dt'), 'order' => $request->getParameter('order', 'desc'));

        $query = Doctrine::getTable("History")
                ->createQuery("h")
                ->select("scheduled_date, sum(value) as 'value', raidid")
                ->groupBy("scheduled_date")
                ->orderBy("scheduled_date desc")
                ->orWhere("h.raidid=?", $raidinfo->getRaidid())
                ->andWhere("h.scheduled_date=?", $raidinfo->getScheduledDate())
                ->andWhere("h.value > 0");

        $query2 = Doctrine::getTable("History")
                ->createQuery("h")
                ->select("scheduled_date, sum(value) as 'value', raidid")
                ->groupBy("scheduled_date")
                ->orderBy("scheduled_date desc")
                ->orWhere("h.raidid=?", $raidinfo->getRaidid())
                ->andWhere("h.scheduled_date=?", $raidinfo->getScheduledDate())
                ->andWhere("h.value < 0");

        $gainResult = $query->execute();
        $lossResult = $query2->execute();

        $loss = 0;
        if ($lossResult->count() > 0)
        {
            $loss = $lossResult->getFirst();
            $loss = $loss["'value'"];
        }

        $gain = 0;
        if ($gainResult->count() > 0)
        {
            $gain = $gainResult->getFirst();
            $gain = $gain["'value'"];
        }

        
        if (!$ajax || ($ajax && $request->hasParameter('itemPage')) )
        {
            $orderby = "dt ".$request->getParameter('order', 'desc');
            if ($request->getParameter('sort', 'dt') != "status")
                $orderby = $request->getParameter('sort', 'dt')." ".$request->getParameter('order', 'desc');
            $query = Doctrine::getTable("ViewHistory")
                    ->createQuery()
                    ->select("reason, dt, itemid, SUM(value) as 'value'")
                    ->where("raidid=?", $raidinfo->getRaidid())
                    ->andWhere("scheduled_date=?", $raidinfo->getScheduledDate())
                    ->andWhere("ttype=?", 'I')
                    ->groupBy("dt");
            if ($orderby != "")
                $query->addOrderBy($orderby);

            $itemsPager = new sfDoctrinePager('ViewHistory', 15);
            $itemsPager->setQuery($query);
            $itemsPager->setPage($request->getParameter('itemPage', 1));
            $itemsPager->init();
            $result = $itemsPager->getResults();

            $items = array();
            if ($result->count() > 0)
            {
                foreach ($result as $history)
                {
                    $array = array();
                    $array['reason'] = $history['reason'];
                    $array['itemid'] = $history['itemid'];
                    $array['isItem'] = false;
                    $match = preg_match('/\[(.*)\]/i', $array['reason'], $words);
                    if ($match)
                    {
                        $array['isItem'] = true;
                        $array['reason'] = $words[0];
                        if ($array['itemid'] == 0)
                        {
                            $match = preg_match_all('/[^:]+/i', $array['reason'], $item);
                            if (isset($item[0][1]))
                                $array['itemid'] = $item[0][1];
                        }
                    }
                    $array['value'] = $history["'value'"];
                    $array['player'] = $history['name'];
                    $array['quality'] = "q4";
                    $array['dt'] = $history['dt'];
                    $array['date'] = date('m/d/y h:i A', strtotime($history['dt']." GMT"));
                    $items[] = $array;
                }
            }

            $tabs['items']['value'] = $items;
            $tabs['items']['pager'] = $itemsPager;

            if ($ajax)
            {
                return $this->renderText(get_partial('tab/'.$tabs['items']['tab'],
                        array(
                        'tab' => $tabs['items'],
                        'ajax' => $ajax,
                        'url_for' => url_for("@view_raid?raidslug=".$raidinfo->getRaid()->getSlug()."&scheduled_date=".$raidinfo->getScheduledDate())
                        ))) ;
            }
        }

        if (!$ajax || ($ajax && $request->hasParameter('pointPage')) )
        {
            $orderby = "dt ".$request->getParameter('order', 'desc');
            if ($request->getParameter('sort', 'dt') != "status")
                $orderby = $request->getParameter('sort', 'dt')." ".$request->getParameter('order', 'desc');
            $query = Doctrine::getTable("ViewHistory")
                    ->createQuery()
                    ->select("reason, dt, itemid, SUM(value) as 'value'")
                    ->where("raidid=?", $raidinfo->getRaidid())
                    ->andWhere("scheduled_date=?", $raidinfo->getScheduledDate())
                    ->andWhere("ttype=?", 'P')
                    //->andWhere("NOT value=?", 0)
                    //->andWhere("date >= ?", $masterTimeLow)
                    //->andWhere("date <= ?", $masterTime)
                    //->limit(5)
                    ->groupBy("dt");
            if ($orderby != "")
                $query->addOrderBy($orderby);
            $pointsPager = new sfDoctrinePager('ViewHistory', 15);
            $pointsPager->setQuery($query);
            $pointsPager->setPage($request->getParameter('pointPage', 1));
            $pointsPager->init();

            $result = $pointsPager->getResults();
            $points = array();
            if ($result->count() > 0)
            {
                foreach ($result as $history)
                {
                    $array = array();
                    $array['reason'] = $history['reason'];
                    $array['itemid'] = $history['itemid'];
                    $array['isItem'] = false;
                    $array['dt'] = $history['dt'];
                    $match = preg_match('/\[(.*)\]/i', $array['reason'], $words);
                    if ($match)
                    {
                        $array['reason'] = $words[0];
                        if ($array['itemid'] == 0)
                        {
                            $match = preg_match_all('/[^:]+/i', $array['reason'], $item);
                            if (isset($item[0][1]))
                                $array['itemid'] = $item[0][1];
                        }
                    }
                    $array['value'] = $history["'value'"];
                    $array['quality'] = "q4";
                    $array['date'] = date('m/d/y h:i A', strtotime($history['dt']." GMT"));
                    $array['player'] = $history['name'];
                    $points[] = $array;
                }
            }

            $tabs['points']['value'] = $points;
            $tabs['points']['pager'] = $pointsPager;

            if ($ajax)
            {
                return $this->renderText(get_partial('tab/'.$tabs['points']['tab'],
                        array(
                        'tab' => $tabs['points'],
                        'ajax' => $ajax,
                        'url_for' => url_for("@view_raid?raidslug=".$raidinfo->getRaid()->getSlug()."&scheduled_date=".$raidinfo->getScheduledDate())
                        ))) ;
            }
        }

        if (!$ajax || ($ajax && $request->hasParameter('playerPage')) )
        {
            $orderby = "name ".$request->getParameter('order', 'desc');
            if ($request->getParameter('sort', 'name') != "status")
                $orderby = $request->getParameter('sort', 'name')." ".$request->getParameter('order', 'asc');
            $query = Doctrine::getTable('ViewRaidPlayers')
                    ->getGuilded()
                    ->andWhere("altrank=?", 0)
                    ->andWhere("altid=?", 1)
                    ->andWhere("raidid IS NOT NULL")
                    ->andWhere("raidid=?", 1)
                    ->andWhere('lifetime > ?', 0);
            if ($orderby != "")
                $query->addOrderBy($orderby);
            $allPlayers = $query->execute();

            $players = null;
            foreach ($allPlayers as $player)
            {
                $players[($player->getFullname())] = array();
            }

            $query = Doctrine::getTable("ViewHistory")
                    ->createQuery()
                    ->distinct()
                    ->select("name, dt, reasonid, value, waitlistflag")
                    ->where("scheduled_date=?", $raidinfo->getScheduledDate());
            if ($orderby != "")
                $query->addOrderBy($orderby);
            $result = $query->execute();

            if ($result->count() > 0)
            {
                foreach ($result as $history)
                {
                    $array = array();
                    $array['isItem'] = false;
                    $array['player'] = ucwords($history['name']);
                    $array['dt'] = $history["dt"];
                    $array['value'] = $history["value"];
                    $array['waitlist'] = $history["waitlistflag"];
                    $array['quality'] = "q4";
                    if (isset($players[($history['name'])]))
                        $players[($history['name'])][$history['dt']] = $array;
                }
            }

            $query = Doctrine::getTable("HistoryGuild")
                    ->createQuery('hg')
                    ->select('dt, scheduled_date')
                    //->where("raidid=?", $raidinfo->getRaidid())
                    ->addOrderBy("dt desc")
                    ->andWhere("raidid=?", $raidinfo->getRaidid())
                    ->andWhere("scheduled_date=?", $raidinfo->getScheduledDate());
            $guildResult = $query->execute();

            $guildRaids = array();
            foreach ($guildResult as $guild)
            {
                if (!isset($guildRaids[$guild['scheduled_date']]))
                    $guildRaids[$guild['scheduled_date']] = array();
                $guildRaids[$guild['scheduled_date']][$guild['dt']] = array('dt' => $guild['dt']);
            }

            $pArray = array();
            foreach ($players as $p => $data)
            {
                $raids = null;
                foreach ($guildRaids as $s => $guild)
                {
                    $array = array();
                    $array['block'] = array();
                    $i = 0;
                    $notMissed = false;
                    $dtStart = 0;
                    foreach ($guild as $dt => $r)
                    {
                        if ($dtStart == 0 || strtotime($dt) < strtotime($dtStart))
                            $dtStart = $dt;
                        if (isset($data[$dt]))
                        {
                            if ($data[$dt]['waitlist'] == 1)
                            {
                                $array['block'][] = 'waitlist';
                                $notMissed = true;
                            }
                            else
                            {
                                $array['block'][] = 'raid';
                                $notMissed = true;
                            }
                        }
                        else
                        {
                            $array['block'][] = 'blank';
                            if ($i == 0)
                                $array['state'] = 'Late';
                            elseif ($i == count($guild[$dt])-1)
                                $array['state'] = (isset($array['state'])?($array['state'].' / '):'').'Left Early';
                        }
                    }
                    $array['date'] = date('m/d/y', strtotime($dtStart." GMT"));
                    $array['player'] = $p;
                    ;
                    if (!$notMissed)
                        $array['state'] = "Missing";
                    else
                        $array['state'] = "Attended";
                    $raids[] = $array;
                }
                $pArray[$p] = $raids[0];
            }
            $players = $pArray;

            if ($request->getParameter('sort', 'name') == "name")
            {
                function acmpa($a, $b)
                {
                    return strcmp($b['player'], $a['player']);
                }
                function acmpd($a, $b)
                {
                    return strcmp($a['player'], $b['player']);
                }
                if ($request->getParameter('order', 'asc') == "asc")
                {
                    $tabs['players']['order'] = "asc";
                    uasort($players, "acmpd");
                }
                else
                {
                    $tabs['players']['order'] = "desc";
                    uasort($players, "acmpa");
                }
                $tabs['players']['sort'] = "name";
            }
            if ($request->getParameter('sort', 'name') == "status")
            {
                function cmpa($a, $b)
                {
                    $cmp = strcmp($a['state'], $b['state']);
                    if (!$cmp)
                        return strcmp($a['player'], $b['player']);
                    return $cmp;
                }
                function cmpd($b, $a)
                {
                    $cmp = strcmp($a['state'], $b['state']);
                    if (!$cmp)
                        return strcmp($a['player'], $b['player']);
                    return $cmp;
                }
                if ($request->getParameter('order', 'asc') == "asc")
                {
                    $tabs['players']['order'] = "asc";
                    uasort($players, "cmpa");
                }
                else
                {
                    $tabs['players']['order'] = "desc";
                    uasort($players, "cmpd");
                }
                $tabs['players']['sort'] = "status";
            }

            $tabs['players']['value'] = $players;
            $tabs['players']['fpager'] = true;
            //$tabs['players']['pager'] = $playersPager;

            if ($ajax)
            {
                return $this->renderText(get_partial('tab/'.$tabs['players']['tab'],
                        array(
                        'tab' => $tabs['players'],
                        'ajax' => $ajax,
                        'url_for' => url_for("@view_raid?raidslug=".$raidinfo->getRaid()->getSlug()."&scheduled_date=".$raidinfo->getScheduledDate())
                        ))) ;
            }
        }
        $this->name = 'raid';
        $this->raidinfo = $raidinfo;
        $this->loss = $loss;
        $this->gain = $gain;
        $this->points = $gain+$loss;
        $this->tabs = $tabs;
        return;
    }


}
